import { type } from 'os';
<!--
 * @Author: your name
 * @Date: 2020-12-07 15:21:11
 * @LastEditTime: 2021-03-23 14:05:02
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \solaxcloud\src\views\warranty\add.vue
-->
<template>
    <div>
        <el-dialog
        :title="$t('edit')"
        :visible="visibleEdit"
        width="1000px"
        @close="()=>{$store.commit('setVisibleEdit',false)}"
        :close-on-click-modal='false'
        >   
            <el-form ref="form" :model="form" label-width="190px" >
                <el-row :gutter="20" >
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('warrantyManage.userName')" prop="loginName" :rules="[{ required: false, message: $t('index_js_notNull')}]">
                            <el-input v-model="form.loginName" :placeholder="$t('pleaseInput')"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('warrantyStatistics.nation')" prop="nation" :rules="[{ required: true, message: $t('index_js_notNull')}]" >
                            <el-select v-model="form.nation" filterable :placeholder="$t('pleaseSelect')" clearable style="width:100%" :disabled='disabledFlag ' @change='nationChange'>
                                <el-option
                                    v-for="item in nationList"
                                    :key="item.enName"
                                    :label="item.enName"
                                    :value="item.enName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0" v-if='form.nation == "UNITED KINGDOM"'>
                        <el-form-item label="Social Energy Installation" prop="IsSEACKIT" :rules="[{ required: true, message: $t('index_js_notNull')}]">
                            <el-radio v-model="form.IsSEACKIT" label="0">Yes</el-radio>
                            <el-radio v-model="form.IsSEACKIT" label="1">No</el-radio>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('warrantyStatistics.userName')" prop="userName" :rules="[{ required: true, message: $t('index_js_notNull')}]">
                            <el-input v-model="form.userName" :placeholder="$t('pleaseInput')"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('warranty.address')" prop="address" :rules="[{ required: true, message: $t('index_js_notNull')}]">
                            <el-input v-model="form.address" :placeholder="$t('pleaseInput')"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('postcode')" prop="postCode" :rules="[{ required: true, message: $t('index_js_notNull')}]">
                            <el-input v-model="form.postCode" :placeholder="$t('pleaseInput')"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('telphone')" prop="phone" :rules="[{ required: true, message: $t('index_js_notNull')}]">
                            <el-input v-model="form.phone" :placeholder="$t('pleaseInput')"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('email')" prop="email" :rules="[{ required: true, message: $t('index_js_notNull')},{ type: 'email', message:$t('user.msg_reg_email'), trigger: ['blur', 'change']}]">
                            <el-input v-model="form.email" :placeholder="$t('pleaseInput')"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('warranty.emailCC.msg')" prop="ccEmail" :rules="[{ required: false, message: $t('index_js_notNull')},{ type: 'email', message:$t('user.msg_reg_email'), trigger: ['blur', 'change']}]">
                            <el-input v-model="form.ccEmail" :placeholder="$t('pleaseInput')" style="width:90%;"></el-input>
                            <el-tooltip class="icon-nmi" placement="top">
                                <div slot="content">
                                    {{$t('warranty.emailCC.will')}}
                                </div>
                                <i class="el-icon-question iconClass"></i>
                            </el-tooltip>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('warranty.addName')" prop="installer" :rules="[{ required: true, message: $t('index_js_notNull')}]">
                            <el-input v-model="form.installer" :placeholder="$t('pleaseInput')"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('warrantyManage.date_address')" prop="installTime" :rules="[{ required: true, message: $t('index_js_notNull')}]" >
                            <el-date-picker
                            v-model="form.installTime"
                            type="date"
                            :placeholder="$t('selectDate')"
                            value-format='yyyy-MM-dd'
                            :clearable='true'
                            :picker-options="pickerOptions"
                            :disabled='disabledFlag '
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('warranty.srotNumber')" prop="inverterSn" :rules="[{ required: true, message: $t('index_js_notNull')}]">
                            <el-input v-model="form.inverterSn" :placeholder="$t('pleaseInput')" @blur="getInverterType" :disabled='disabledFlag '></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('invoice.deviceType')" prop="model" :rules="[{ required: true, message: $t('index_js_notNull')}]">
                            <el-select v-model="form.model" filterable :placeholder="$t('pleaseSelect')" clearable style="width:100%" :disabled="disabledFlag " >
                                <el-option
                                    v-for="item in inverterType"
                                    :key="item.sid"
                                    :label="item.inverterTypeName"
                                    :value="item.inverterTypeName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('warrantyManage.extension_code')" prop="delayCode" :rules="[{ required: false, message: $t('index_js_notNull')}]">
                            <el-input v-model="form.delayCode" :placeholder="$t('pleaseInput')" :disabled='disabledFlag '></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0" v-if='returnOtherName(form.model) == 99'>
                        <el-form-item :label="$t('warranty.other')" prop="model" :rules="[{ required: true, message: $t('index_js_notNull')}]">
                            <el-input v-model="form.deviceTypeName" :placeholder="$t('pleaseInput')" :disabled="disabledFlag "></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('warrantyManage.promotion_code')" prop="saleCode" :rules="[{ required: false, message: $t('index_js_notNull')}]">
                            <el-input v-model="form.saleCode" :placeholder="$t('pleaseInput')" :disabled='disabledFlag '></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20" style="background-color:#f6f6f6;margin-bottom:5px;" v-for='(value,key,index) in form.batteryListForm' :key='index'>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('warrantyStatistics.batterySN')" :prop="'batteryListForm.item'+(index+1)+'.sn'" :rules="[{ required: false, message: $t('index_js_notNull')}]">
                            <el-input v-model="form.batteryListForm[key]['sn']" :placeholder="$t('pleaseInput')" :disabled="disabledFlag &&returnExamineBattery(form.batteryListForm[key]['sn'],form.batteryListForm[key]['id'])" @blur="blurBatterySn(form.batteryListForm[key]['sn'],form.batteryListForm[key])"></el-input>
                            
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="0">
                        <el-form-item :label="$t('warranty.newAddData')" :prop="'batteryListForm.item'+(index+1)+'.date'" :rules="[{ required: value.sn?true:false, message: $t('index_js_notNull')}]">
                            <el-date-picker
                            v-model="form.batteryListForm[key]['date']"
                            type="date"
                            :placeholder="$t('selectDate')"
                            value-format='yyyy-MM-dd'
                            :clearable='true'
                            :picker-options="pickerOptions"
                            :disabled="disabledFlag &&returnExamineBattery(form.batteryListForm[key]['sn'],form.batteryListForm[key]['id'])"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2" :offset="0" >
                        <span style="display: block;line-height: 35px;color:green;  font-size: 18px;float:left;margin-right:10px;" @click='pushBatterySn' v-if='index == Object.keys(form.batteryListForm).length-1'><i class="el-icon-circle-plus"></i></span>
                        <span style="display: block;line-height: 35px;color:red;  font-size: 18px;float:left;" @click='deleteBatterySn(value)' v-if="!(disabledFlag && returnExamineBattery(form.batteryListForm[key]['sn']),form.batteryListForm[key]['id'])"><i class="el-icon-error"></i></span>
                    </el-col>
                    
                </el-row>
                <!-- <el-row :gutter="20">
                    <el-col :span="11" :offset="13">
                        <p style="color:red;">电池SN可批量填写，请以英文 ',' 逗号分割。</p>
                    </el-col>
                </el-row> -->
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="()=>{$store.commit('setVisibleEdit',false)}">{{$t('cancel')}}</el-button>
                <el-button type="primary" @click="save('form')">{{$t('sure')}}</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    components: {

    },
    props: {
        nationList:{
            type:Array,
            default:()=>{ return []}
        },
        inverterType:{
            type:Array,
            default:()=>{return []}
        },
        editRow:{
            type:Object,
            default:()=>{return {}}
        },
        disabledFlag:{
            type:Boolean,
            default:true
        },
        disabledFlag2:{
            type:Boolean,
            default:true
        }
    },
    data() {
        return {
            form:{
                loginName:'',
                nation:'',
                userName:'',
                address:'',
                postCode:'',
                phone:'',
                installTime:'',
                installer:'',
                inverterSn:'',
                model:'',
                email:'',
                delayCode:'',
                saleCode:'',
                batterySN:'',
                IsSEACKIT:'',
                ccEmail:'',
                batteryList:[],
                batteryListForm:{item1:{sn:'',date:'',flag:'0'}},
                deviceTypeName:'',
            },
            typeList:[],
            pickerOptions:{ //禁用今天之后的时间
                disabledDate(time) {
                    return time.getTime() > Date.now()
                }
            },
            oldSN:'',
            flagType:false,
            copyInverter:[],
            flagInverter:true
        };
    },
    computed: {
        visibleEdit(){
            return this.$store.state.sysStore.visibleEdit
        },
        deviceType(){
            let type= ''
            this.inverterType.forEach(item =>{
                if(item.inverterTypeName == this.form.model){
                    type = item.inverterType
                }
            })
            return type
        }
    },
    watch: {
        inverterType:{
            handler(nv,ov){
                if(nv && this.flagInverter){
                    this.copyInverter = nv
                    this.flagInverter = false
                }
            }
        },
        visibleEdit:{
            handler(nv,ov){
                if(nv){
                    this.qualityGetById()
                    // this.copyInverter = this.inverterType
                }
            }
        }
    },
    created() {

    },
    mounted() {
        
    },
    methods: {
        nationChange(){
            if(this.form.nation == 'JAPAN'){
                this.orderpaypalconfigGetInverterTypeList()
                this.form.model = ''
            }else{
                this.inverterType = this.copyInverter
            }
        },
        async orderpaypalconfigGetInverterTypeList(){
            let res = await this.API.orderpaypalconfigGetInverterTypeList({
                inverterTypeName:this.form.nation
            })
            this.inverterType = res
        },
        returnExamineBattery(sn,id){
            if(!id){
                return false
            }
            if(this.editRow.unlockBattery){
                if(this.editRow.unlockBattery.indexOf(sn) != -1){
                    return true
                }else{
                    return false
                }
            }else{
                return false
            }
        },
        async deleteBatterySn(value){
            if(value.id){
                let res = await this.API.crmbatteryqualityDelete({
                    id:value.id
                })
                if(this.comm.showMsg(res.success)){
                    this.qualityGetById()
                }
            }else{
                let obj = {}
                for(let key in this.form.batteryListForm){
                    if(this.form.batteryListForm[key].index != value.index){
                        obj[key] = this.form.batteryListForm[key]
                    }
                }
                this.form.batteryListForm = obj
            }
            
        },
        getRandomNumber (min, max) {
            return Math.floor(Math.random() * (max - min + 1) + min)
        },
        returnOtherName(code){
            let type = ''
            this.inverterType.forEach(item=>{
                if(item.inverterTypeName == code){
                    type = item.inverterType
                }
            })
            return type
        },
        blurBatterySn(sn,obj){
            let reg = /^[A-Za-z0-9]+$/
            if(sn){
                var inverterSn = sn
                inverterSn = inverterSn.toUpperCase()
                sn = inverterSn
                obj.sn = sn
            }
            if(!reg.test(sn)){
                this.comm.showMsg(false,this.$t('warranty.batchSend.message5'))
                return false;
            }
            if(sn.split('').length != 14){
                this.comm.showMsg(false,this.$t('warranty.batchSend.message5'))
                return false;
            }
        },
        async crmbatteryqualityCheckBatterySN(){
            let res = await this.API.crmbatteryqualityCheckBatterySN({
                batterySNList:this.returnSoltSn()
            })
            if(res.success == false){
				if(res.object.length>0){
                    this.comm.showMsg(false,this.$t('warranty.newAddDataMsgRepeat')+res.object)
				}else{
                    this.comm.showMsg(false,this.$t('index.control_fail'))
				}
			}else{
				this.saveSend()
			}
        },
        async saveSend(){
            let snArr = []
            for(let key in this.form.batteryListForm){
                if(this.form.batteryListForm[key].sn){
                    snArr.push(this.form.batteryListForm[key])
                }
            }
            if(this.form.IsSEACKIT == null){
                this.form.IsSEACKIT = ''
            }
            let deleteBatteryIds = []
            snArr.forEach(item =>{
                if(item.id){
                    if(!item.sn){
                        deleteBatteryIds.push(item.id)
                    }
                }
            })
            let newObj = JSON.parse(JSON.stringify(this.form))
            delete newObj.batteryList
            delete newObj.batteryListForm
            if(this.disabledFlag){
                delete newObj.batterySN
                delete newObj.nation
                delete newObj.inverterSn
                delete newObj.delayCode
                delete newObj.saleCode
                delete newObj.installTime
            }
            
            let res = await this.API.qualityUpdate(Object.assign({},newObj,{
                deviceType:this.deviceType,
                id:this.editRow.sid,
                batterySNList:snArr.map(item=>{return item.sn}),
                batteryInstallTime:snArr.map(item=>{return item.date}),
                batteryEnableFlag:snArr.map(item=>{return item.flag}),
                batteryIdList:snArr.map(item=>{return item.id}),
                deleteBatteryIds:deleteBatteryIds.map(item=>{return item})
            }))
            if(res.success == false){
				if(res.object=='1'){
                    this.comm.showMsg(false,this.$t('warrantyManage.msgErroy1'))
					return
				}
				if(res.object=='2'){
                    this.comm.showMsg(false,this.$t('warrantyManage.msgErroy2'))
					return
				}
				if(res.object=='3'){
                    this.comm.showMsg(false,this.$t('warrantyManage.msgErroy3'))
					return
				}
				if(!res.object){
                    this.comm.showMsg(false,res.msg)
					return
				}
			}else{
                // closeDialog("editDialog");
                this.$store.commit('setVisibleEdit',false)
                this.$emit('uploadData',true)
				// $('#dataTable').bootstrapTable('refresh');
			}
        },
        returnSoltSn(){
            let arr = []
            let lengths = Object.keys(this.form.batteryListForm)
            for(let i = 0;i<lengths.length;i++){
                if(i<this.form.batteryList.length){
                    if(this.form.batteryListForm[lengths[i]].sn !=this.form.batteryList[i].batterySN){
                        arr.push(this.form.batteryListForm[lengths[i]].sn)
                    }
                }else{
                     arr.push(this.form.batteryListForm[lengths[i]].sn)
                }
            }
            return arr.join(',')
        },  
        pushBatterySn(){
            let length = Object.keys(this.form.batteryListForm).length
            this.$set(this.form.batteryListForm,`item${length+1}`,{})
            this.$set(this.form.batteryListForm[`item${length+1}`],'sn','')
            this.$set(this.form.batteryListForm[`item${length+1}`],`date`,'')
            this.$set(this.form.batteryListForm[`item${length+1}`],`flag`,'1')
            this.$set(this.form.batteryListForm[`item${length+1}`],`index`,this.getRandomNumber(1000000,9999999))
        },
        async qualityGetById(){
            let res = await this.API.qualityGetById({
                id:this.editRow.sid
            })
            for(let key in this.form){
                this.form[key] = res[key] || ''
            }
            if(res.nation == 'JAPAN'){
                this.orderpaypalconfigGetInverterTypeList()
            }
            this.editRow.unlockBattery = res.unlockBattery
            this.form.IsSEACKIT = res.isSEACKIT == null ? '': res.isSEACKIT + ''
            this.form.batteryListForm = {item1:{sn:'',date:'',flag:0}}
            if(this.form.batteryList.length>0){
                for(let i = 0;i<this.form.batteryList.length;i++){
                    this.$set(this.form.batteryListForm,`item${i+1}`,{})
                    this.$set(this.form.batteryListForm[`item${i+1}`],'sn',this.form.batteryList[i].batterySN)
                    this.$set(this.form.batteryListForm[`item${i+1}`],`date`,this.form.batteryList[i].installTime.split(' ')[0])
                    this.$set(this.form.batteryListForm[`item${i+1}`],`flag`,this.form.batteryList[i].enableFlag)
                    this.$set(this.form.batteryListForm[`item${i+1}`],`id`,this.form.batteryList[i].sid)
                    this.$set(this.form.batteryListForm[`item${i+1}`],`index`,i+1)
                }
            }
            if(res.deviceType == 99){
                this.form.model = this.$t('warranty.other')
            }
        },
        async getInverterType(){
            if(!(this.form.inverterSn && this.form.inverterSn != this.oldSN)){
                return
            }
            let res = await this.API.orderpaypalconfigGetInverterType({
                inverterSn:this.form.inverterSn
            })
            if(res){
                this.form.model = res.inverterTypeName
                this.flagType = true
            }else{
                this.flagType = false
            }
            this.oldSN = this.form.inverterSn
        },
        async qualitySave(){
            let res = await this.API.crmbatteryqualityCheckBatterySN({
                batterySNList:this.form.batterySN
            })
            if(res.success == false){
                if(res.object.length>0){
                    this.comm.showMsg(false,this.$t('warranty.newAddDataMsgRepeat')+res.object)
                }else{
                    this.comm.showMsg(false,this.$t('index.control_fail'))
                }
                return
            }
            let res2 = await this.API.qualitySave(Object.assign({},this.form,{deviceType:this.deviceType}))
            if(this.comm.showMsg(res2.success,this.$t('warranty.successsMsg'))){
                this.$store.commit('setNewVisiblePvModules',false)
                this.$emit('uploadData',true)
            }else{
                if(res2.object=='1'){
                    // openMsg(getText("#msgErroy1"));
                    this.comm.showMsg(false,this.$t('warrantyManage.msgErroy1'))
					return
				}
				if(res2.object=='2'){
                    // openMsg(getText("#msgErroy2"));
                    this.comm.showMsg(false,this.$t('warrantyManage.msgErroy2'))
					return
				}
				if(res2.object=='3'){
                    // openMsg(getText("#msgErroy3"));
                    this.comm.showMsg(false,this.$t('warrantyManage.msgErroy3'))
					return
				}
				if(!res2.object){
					openMsg(res2.msg);
					return
				}
            }
        },
        save(formName){
            this.$refs[formName].validate((valid) => {
              if (valid) {
                  this.crmbatteryqualityCheckBatterySN()
              } else {
                console.log('error submit!!');
                return false;
              }
            });
        },
    },
};
</script>

<style  lang="less" scoped>

</style>

